package com.hulk.dryad.admin.security;


import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.hulk.dryad.admin.api.dto.SysUserDTO;
import com.hulk.dryad.admin.api.dto.UserInfoDTO;
import com.hulk.dryad.admin.mapstruct.UserInfoStruct;
import com.hulk.dryad.common.constant.CommonConstants;
import com.hulk.dryad.common.constant.SecurityConstants;
import com.hulk.dryad.common.constant.enums.BEC;
import com.hulk.dryad.common.util.WebUtils;
import com.hulk.dryad.persistence.admin.AdminUser;
import com.hulk.dryad.persistence.entity.SysUserModel;
import com.hulk.dryad.persistence.entity.UserInfoModel;
import com.hulk.dryad.persistence.service.SysUserService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @author kim
 */
@Slf4j
@Service
@AllArgsConstructor
public class AdminSysUserDetailsServiceImpl implements AdminSysUserDetailsService {

	private final SysUserService sysUserService;


	/**
	 * 用户密码登录
	 *
	 * @param username 用户名
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String username) {

		SysUserModel user = sysUserService.getOne(Wrappers.<SysUserModel>query().lambda().eq(SysUserModel::getUsername, username));
		if (user == null) {
			throw new UsernameNotFoundException(BEC.E_2015.toString());
		}
		UserInfoModel userInfoModel = sysUserService.findUserInfo(user);
		UserInfoDTO userInfoDTO = UserInfoStruct.INSTANCE.from(userInfoModel);
		HttpServletRequest request = WebUtils.getRequest();
		UserDetails userDetails = getUserDetails(userInfoDTO, request);

		return userDetails;
	}

	/**
	 * 构建userDetails
	 *
	 * @param info 用户信息
	 * @return
	 */
	private UserDetails getUserDetails(UserInfoDTO info, HttpServletRequest request) {

		Set<String> dbAuthsSet = new HashSet<>();
		if (ArrayUtil.isNotEmpty(info.getRoles())) {
			Arrays.stream(info.getRoles()).forEach(roleId -> {
				/* 获取角色*/
				dbAuthsSet.add(SecurityConstants.ROLE + roleId);
			});
			Arrays.stream(info.getRoleCodes()).forEach(roleCode -> {
				/* 获取用户组,此处以角色标识作为组名 */
				/* Activiti拾取适用*/
				dbAuthsSet.add(SecurityConstants.GROUP + roleCode.substring(SecurityConstants.ROLE.length()));
			});
			//ROLE_ADMIN 用户添加ACTIVITI权限
			if(dbAuthsSet.contains("ROLE_1")){
				dbAuthsSet.add(SecurityConstants.ROLE_ACTIVITI_ADMIN);
			}else{
				dbAuthsSet.add(SecurityConstants.ROLE_ACTIVITI_USER);
			}
			/* 获取资源*/
			dbAuthsSet.addAll(Lists.newArrayList(info.getPermissions()));
		}
		Collection<? extends GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		SysUserDTO user = info.getSysUserDTO();
		String tenantId = request.getHeader(CommonConstants.TENANT_ID);
		if (StrUtil.isBlank(tenantId)) {
			tenantId = request.getParameter(CommonConstants.TENANT_ID);
		}
		user.setTenantId(tenantId);
		boolean enabled = StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL);
		/* 构造security用户*/
		return new AdminUser(user.getUserId(), user.getDeptId(), user.getPhone(), user.getAvatar(), user.getTenantId(), user.getUsername(),
				SecurityConstants.BCRYPT + user.getPassword(), enabled, true, true,
				!CommonConstants.STATUS_LOCK.equals(user.getLockFlag()), authorities);
	}

}
